<?php

namespace app\index\controller;

use app\common\entity\Config;
use app\common\entity\User;
use app\common\entity\Market;
use app\common\entity\UserLevelSend;
use app\common\entity\MywalletLog;
use think\Db;
use app\common\entity\Proportion;

class Wallet  {

    public function xxx(){
        $userModel = new User();
        $one_partner = $userModel->alias('u')
            ->join('partnerr p','p.user_id = u.id and p.type=1 and p.status=2')
            ->field('p.*')
            ->where('u.partner',1)->select()->toArray();

        $two_partner = $userModel->alias('u')
            ->join('partnerr p','p.user_id = u.id and p.type=2 and p.status=2')
            ->field('p.*')
            ->where('u.partner2',1)->select()->toArray();

        foreach($one_partner as $k=>$v){
            foreach($two_partner as $key=>$val){
                if($v['city'] == $val['city']){
                    $one_partner[$k]['son'][] = $val;
                    unset($two_partner[$key]);
                }
            }
        }
        foreach($one_partner as $k=>$v){
            echo $v['province'].$v['city'].$v['area'].$this->user_is_bind($v['user_id']).".1\n";
            if(isset($v['son'])){
                foreach($v['son'] as $key=>$val){
                    echo $val['province'].$val['city'].$val['area'].$this->user_is_bind($v['user_id']).".2\n";
                }
            }

        }

            foreach($two_partner as $key=>$val){
                echo $val['province'].$val['city'].$val['area'].$this->user_is_bind($v['user_id']).".3\n";
            }
    }


    public function day(){
        //等级分佣
        $marketList = Market::where('end_time','>',strtotime(date('Y-m-d',strtotime("-1 day"))))->select();

        $sumMoney = 0;
        foreach($marketList as $k=>$v){
            $sumMoney += bcmul($v['num'],$v['charges'],5);
        }

        $UserLevelSend = UserLevelSend::where('level','>',0)->select();

        foreach($UserLevelSend as $k=>$v){
            $UserLevelSend[$k]['list'] = User::where('level',$v['level'])->where('status',1)->select()->toArray();
        }

        foreach($UserLevelSend as $k=>$v){

            if(empty($v['list'])){continue;}
            $team_ratio= bcmul($sumMoney,$v['team_ratio'],5);
            $money = bcdiv($team_ratio,count($v['list']),5);

            foreach($v['list'] as $key=>$val){
                if($this->user_is_bind($val['id'])){
                    echo '等级：'.$v['level'].' uid'.$val['id'].'用户'.$val['mobile'].'得到等级分佣'.$money.'福豆('.$sumMoney.'*'.$v['team_ratio'].'/'.count($v['list']).')';echo "\n";
                    MywalletLog::addLog($val['id'],$money,1,date('Y-m-d').'等级奖励',4,1);
                }

            }

        }

        //区域分佣

        $userModel = new User();
        $one_partner = $userModel->alias('u')
            ->join('partnerr p','p.user_id = u.id and p.type=1 and p.status=2')
            ->field('p.*')
            ->where('u.partner',1)->select()->toArray();

        $two_partner = $userModel->alias('u')
            ->join('partnerr p','p.user_id = u.id and p.type=2 and p.status=2')
            ->field('p.*')
            ->where('u.partner2',1)->select()->toArray();

        foreach($one_partner as $k=>$v){
            foreach($two_partner as $key=>$val){
                if($v['city'] == $val['city']){
                    $one_partner[$k]['son'][] = $val;
                    unset($two_partner[$key]);
                }
            }
        }



        //无区代理的市代理
        $notson = Config::getValue('city_partner')/100;
        //区代理
        $son = Config::getValue('area_partner')/100;
        //有区代理的市代理
        $haveson = $notson - $son;


        foreach($one_partner as $k=>$v){
            echo $this->user_is_bind($v['user_id']).".1\n";

                #对应市产生的手续费
                $sumNumber = $this->getRegionCharges($v['city']);
                if(empty($v['son'])){
                    #无区市代理分红分红
                    $money = bcmul($sumNumber,$notson,2);
                }else {
                    #*有区市代理分红
                    $money = bcmul($sumNumber, $haveson, 2);
                    foreach ($v['son'] as $key => $val) {
                        echo $this->user_is_bind($val['user_id']).".2\n";
                        if ($this->user_is_bind($val['user_id'])) {
                            #对应区产生的手续费
                            $sonSumNumber = $this->getRegionCharges($val['city'], $val['area']);
                            #*区代理分红
                            $sonMoney = bcmul($sonSumNumber, $son, 2);
                            if ($sonSumNumber > 0) {
                                echo $val['province'] . $val['city'] . $val['area'] . $sonSumNumber . "区1分佣'.$sonMoney.'\n\n";
                            }

                            MywalletLog::addLog($val['user_id'], $sonMoney, 1, '区域奖', 6, 1);
                        }
                    }
                }
                if ($this->user_is_bind($v['user_id'])){
                    if($sumNumber > 0) {
                        echo $v['province'] . $v['city'] . $v['area'] . $sumNumber . "市分佣'.$money.'\n\n";
                    }
                    MywalletLog::addLog($v['user_id'],$money,1,'市域奖',6,1);
                }

        }
        #无市代理的区代理分佣
        foreach($two_partner as $key=>$val){
            echo $this->user_is_bind($val['user_id']).".3\n";
            if ($this->user_is_bind($val['user_id'])) {
                #对应区产生的手续费
                $sonSumNumber = $this->getRegionCharges($val['city'], $val['area']);
                #*区代理分红
                $sonMoney = bcmul($sonSumNumber, $son, 2);
                if ($sonSumNumber > 0) {
                    echo $val['province'] . $val['city'] . $val['area'] . $sonSumNumber . "区2分佣'.$sonMoney.'\n\n";
                }
                MywalletLog::addLog($val['user_id'], $sonMoney, 1, '区域奖', 6, 1);
            }
        }
    }

    private  function getRegionCharges($city,$area = ''){
        $where = ['u.city'=>$city];
        if($area){
            $where['u.area'] = $area;
        }
        $sonSum = Market::alias('m')
            ->join('user u','u.id = m.from_user_id')
            ->field('m.num,m.charges')
            ->where($where)
            ->where('m.end_time','>',strtotime(date('Y-m-d',strtotime("-1 day"))))
            ->select();
        $sonSumNumber = 0;
        foreach($sonSum as $kk=>$vv){
            $sonSumNumber += bcmul($vv['num'],$vv['charges'],5);
        }
        return $sonSumNumber;
    }

    public function month(){
        $last_month = strtotime('last month').','.(strtotime(date('Y-m-1'))-1);
        $account_pos = Db::name('account_pos')->alias('a')
            ->join('pos_log l','l.sn_id = a.sn_id')
            ->join('user u','u.id = a.user_id')
            ->field('a.user_id,sum(l.money) as number,u.pid,u.id')
            ->whereBetween('l.create_time',$last_month)
            ->group('a.user_id')
            ->select();
        print_r($account_pos);
        $pos_water_reward = Config::getValue('pos_water_reward');
        $account_pos_water_reward = Config::getValue('account_pos_water_reward');
        $today_market = Proportion::where('date', '<=', date('Y-m-d'))->order('date desc')->value('ratio');

        foreach($account_pos as $k=>$v){
            if ($this->user_is_bind($v['user_id'])) {
                $money = bcdiv(bcmul($pos_water_reward, $v['number']), $today_market, 2);
                $my_money = bcdiv(bcmul($account_pos_water_reward, $v['number']), $today_market, 2);
                print_r($my_money);
                echo "<br/>";
                if($v['pid']){
                    if($this->user_is_bind($v['pid'])){
                        $pid = MywalletLog::addLog($v['pid'], $money, 1, 'pos机流水返佣', 5, 1);
                    }
                }
                $id = MywalletLog::addLog($v['id'], $my_money, 1, 'pos机流水返佣', 5, 1);
            }
        }

    }

    /**
     * @param $shllFathers      分佣的人
     * @param $market           战队
     * @param $UserLevelSend    会员等级列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function checkReward($shllFathers,$market,$UserLevelSend){
        $list = [];
        $money = bcmul($market['num'],$market['charges'],5);
        foreach($shllFathers as $k=>$v){
            if($v['level'] != 0){
                $list[] = $v;
            }
        }
        $levelSend = [];
        foreach($UserLevelSend as $k=>$v){
            $item = ['level'=> $v['level'],'list'=>[]];
            foreach($list as $key=>$val){
                if($val['level'] == $v['level']){
                    $item['list'][] = $val;
                }
            }

            $team_ratio = empty($item['list'])?$v['team_ratio']:bcdiv($v['team_ratio'],count($item['list']),5);
            $item['money'] = bcmul($money,$team_ratio,5);
            $levelSend [] = $item;
        }

        foreach($levelSend as $k=>$v){
            foreach($v['list'] as $key=>$val){

                echo 'uid'.$val['id'].'用户'.$val['mobile'].'得到来自uid'.$market['from_user_id'].'的等级分佣'.$v['money'].'福豆';echo "\n";

                MywalletLog::addLog($val['id'],$v['money'],1,$market['from_user_id'],4,1);
            }
        }
    }



    public function fanTree($data, $id){
        $list = array();
        foreach($data as $v) {
            if($v['id'] == $id) {
                $item = $this->fanTree($data, $v['pid']);
                array_push($list, $v);
                if(!empty($item)) {
                    $list = array_merge($list, $item);
                }

            }
        }
        return $list;
    }


    public function notNull(){
        $users = User::where('is_active',1)->whereNotNull('pos')->where('pos','<>','')->order('id desc')->select();
        print_r($users);
    }

    #升级
    public function update_level(){
        $users = User::where('is_active',1)->whereNotNull('pos')->where('pos','<>','')->order('id desc')->select();
        foreach($users as $k=>$v){
            $this->upLevel($v['id'],$users);
        }
    }
    public function upLevel($uid,$userList){

        $tree = $this->fanTree2($userList,$uid);

        $finds = User::where('pid',$uid)->where('is_active',1)->whereNotNull('pos')->where('pos','<>','')->select();
        $gold = 0;
        $diamond = 0;
        $platinum = 0;
        foreach($finds as $k=>$v){
            if($v['level'] == 1){$gold++;}
            if($v['level'] == 2){$diamond++;}
            if($v['level'] == 3){$platinum++;}
        }
        $user_level_send = UserLevelSend::where('level','>',0)->order('level desc')->select();
        $userInfo = User::where('id',$uid)->find();
        foreach($user_level_send as $k=>$v){

            if(count($finds) >= $v['zhitui']
                && $gold >= $v['gold']
                && $diamond >= $v['diamond']
                && $platinum >= $v['platinum']
                && count($tree) >= $v['team_total_num']){

                if($v['level'] > $userInfo['level']){
                    $mobile = User::where('id',$uid)->value('mobile');
                    echo '用户'.$mobile.'升到'.$v['level'].'级'."\n";
                    User::where('id',$uid)->update(['level'=>$v['level']]);
                    break;
                }
            }
        }
    }

    public function fanTree2($data, $id){
        $list = array();
        foreach($data as $v) {
            if($v['pid'] == $id) {
                $item = $this->fanTree2($data, $v['id']);
                array_push($list, $v);
                if(!empty($item)) {
                    $list = array_merge($list, $item);
                }

            }
        }
        return $list;
    }



    #过时封号
    public function fenghao(){
        $marketList = Market::where('status','in','2,3')->select();

        $time_end = Config::getValue('time_end') * 3600;

        foreach($marketList as $k=>$v){
            if($v['status'] == 2){
                $start_time = $v['matching_time'];
            }else{
                $start_time = $v['pay_time'];
            }
            $surplus_time = $time_end - (time() - $start_time);
            if($surplus_time <= 0){
                $uid = 0;
                echo $v['id'];echo "\n";
                $update = ['end_time'=>time()];
                $total = $v['num'];
                if($v['status'] == 2){
                    $uid = $v['user_id'];
                    echo 'status = '.$v['status'];echo "\n";
                    #订单结束，fbb返还
                    $update['status'] = 5;
                    Market::where('id',$v['id'])->update($update);
                    //返币
                    $charges = bcmul($total, Config::getValue('toShell'),5);
                    MywalletLog::addLog($v['from_user_id'],$total,1,'交易'.$v['id'].'过时返币',19,1);
                    MywalletLog::addLog($v['from_user_id'],$charges,1,'交易'.$v['id'].'过时返手续费',20,1);
                }else{
                    $uid = $v['from_user_id'];
                    echo 'status = '.$v['status'];echo "\n";
                    #强制完成
                    $update['status'] = 4;
                    Market::where('id',$v['id'])->update($update);
                    //强制完成
                    MywalletLog::addLog($v['user_id'], $total, 1, '交易收入', 1, 1);
                }
                //封号
                User::where('id',$uid)->update(['forbidden_time'=>time(),'status'=>-1]);
            }
        }
    }



    #判断用户有没有绑定机器
    private function user_is_bind($uid){
        $user = User::where('id',$uid)->find();
        if($user['pos'] == '' || $user['pos'] == null){
            return false;
        }else{
            return true;
        }
    }

}
